<?php

declare(strict_types=1);

namespace app\wx\controller;


use app\wx\model\SystemAdmin;
use EasyWeChat\Factory;
use think\Controller;

class App extends Controller
{
    /**
     *授权成功跳转页 
     */
    public function index()
    {
        return $this->fetch();
    }
    public function app()
    {
        $app_id = env('app_id') ?? 'wxbb5a4404d56eee59';
        $secret = env('secret') ?? '55a63f585540c402737b1d5bf6f3b961';
        $token = env('token') ?? 'tan_xianwei';
        $config = [
            'app_id' => $app_id,
            'secret' => $secret,
            'token'  => $token
        ];
        return Factory::officialAccount($config);
    }
    /***
     * 微信授权绑定
     */
    public function callback()
    {
        $app_id = env('app_id') ?? 'wxbb5a4404d56eee59';
        $secret = env('secret') ?? '55a63f585540c402737b1d5bf6f3b961';
        $token = env('token') ?? 'tan_xianwei';
        $aid = $this->request->param('aid');
        $config = [
            'app_id' => $app_id,
            'secret' => $secret,
            'token'  => $token,
            'oauth' => [
                'scopes'  => ['snsapi_userinfo'],
                'callback'  => 'http://www.ydcrms.com:8013/wx/app/bb?aid=' . $aid,
            ]
        ];
        $app = Factory::officialAccount($config);
        $response = $app->oauth->redirect();
        return $response;
    }

    public function bb()
    {
        $app = $this->app();
        $user = $app->oauth->user();
        $openid = $user->getId();
        $aid = $this->request->param('aid');
        $dt = SystemAdmin::find($aid);
        if (empty($dt['open_id'])) {
            $admin = new SystemAdmin;
            $admin->save([
                'open_id' => $openid,
            ], ['id' => $aid]);
            $this->success('授权成功', 'index');
        }
    }
}
